import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/config/kq_core_global.dart';
import 'package:kq_flutter_widgets/widgets/bottomSheet/sheets/kq_action_list_bottom_sheet.dart';
import 'package:kq_flutter_widgets/widgets/bottomSheet/sheets/kq_date_picker_bottom_sheet.dart';
import 'package:kq_flutter_widgets/widgets/bottomSheet/sheets/kq_linkage_picker_bottom_sheet.dart';
import 'package:kq_flutter_widgets/widgets/bottomSheet/sheets/kq_list_picker_bottom_sheet.dart';

import '../../resources/l10n/kq_intl.dart';
import 'kq_bottom_sheet.dart';
import 'sheets/kq_bottom_sheet_view.dart';
import 'sheets/kq_date_range_picker_bottom_sheet.dart';
import 'sheets/kq_options_bottom_sheet.dart';

/// 通用底部弹窗
class KqBottomSheetManager {
  static showBottomSheet(
    String title,
    Widget child, {
    double? childHeight,
    double? childMaxHeight,
    bool? isShowBottomBtn,
    CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.start,
    Function(int index)? tabIndexBlock,
    String? cancelStr,
    Color? cancelColor,
    Color? cancelBgColor,
    Widget? cancelCustomWidget,
    String? confirmStr,
    Color? confirmColor,
    Color? confirmBgColor,
    Widget? confirmCustomWidget,
    double? iconWidth,
    double? iconHeight,
    double? iconRight,
    bool? isTitleBottomLine,
  }) {
    showModalKqBottomSheet(
      context: KqCoreGlobal.globalContext,
      isScrollControlled: true,
      barrierColor: Colors.black.withOpacity(0.2),
      isDismissible: true,
      builder: (context) {
        return KqBottomSheetView(
          childHeight: childHeight,
          childMaxHeight: childMaxHeight,
          iconHeight: iconHeight,
          iconWidth: iconWidth,
          iconRight: iconRight,
          title: title,
          isBottomBtn: isShowBottomBtn ?? true,
          tabIndexBlock: tabIndexBlock,
          cancelStr: cancelStr,
          cancelColor: cancelColor,
          isTitleBottomLine: isTitleBottomLine ?? true,
          cancelBgColor: cancelBgColor,
          confirmStr: confirmStr,
          confirmColor: confirmColor,
          confirmBgColor: confirmBgColor,
          crossAxisAlignment: crossAxisAlignment,
          cancelCustomWidget: cancelCustomWidget,
          confirmCustomWidget: confirmCustomWidget,
          child: child,
        );
      },
    );
  }

  /// 纯日期选择 （年月日）
  /// [defDateMode] ： [KqDatePickerMode] 决定选择年，还是年月，还是年月日
  /// [dateModes] ： 用于头部选择“按年”，“按月”切换。
  /// [customHeaders] ：自定义头部组件
  static showDatePicker({
    String? title,
    DateTime? minDateTime,
    DateTime? maxDateTime,
    DateTime? initialDateTime,
    String? leftBtnText,
    String? rightBtnText,
    List<KqDatePickerMode>? dateModes,
    KqDatePickerMode? defDateMode,
    List<Widget>? customHeaders,
    bool Function(DateTime dateTime, List<int> selectedIndex)? onConfirm,
    bool Function(DateTime dateTime, List<int> selectedIndex,
            KqDatePickerMode? dateMode)?
        onConfirmWithMode,
    Function(DateTime dateTime, List<int> selectedIndex)? onChange,
    Function()? onDismiss,
    Function()? onCancel,
  }) {
    return showModalKqBottomSheet(
      context: KqCoreGlobal.globalContext,
      backgroundColor: Colors.transparent,
      barrierColor: Colors.black.withOpacity(0.2),
      isScrollControlled: true,
      builder: (context) => KqDatePickerBottomSheet(
          initialDateTime: initialDateTime ?? DateTime.now(),
          pickerMode: KqDateTimePickerMode.date,
          minDateTime: minDateTime,
          maxDateTime: maxDateTime,
          leftBtnText: leftBtnText,
          rightBtnText: rightBtnText,
          pickerTitleConfig: KqPickerTitleConfig(
              titleContent: title ?? KqIntl.currentResource.pleaseChooseTime),
          dateModes: dateModes,
          defDateMode: defDateMode,
          onConfirm: onConfirm,
          customHeaders: customHeaders,
          onConfirmWithMode: onConfirmWithMode,
          onCancel: onCancel,
          onChange: onChange),
    ).then((value) => {onDismiss?.call()});
  }

  /// 纯时间选择对话框（时分秒）
  static showTimePicker({
    String? title,
    DateTime? minDateTime,
    DateTime? maxDateTime,
    DateTime? initialDateTime,
    String? leftBtnText,
    String? rightBtnText,
    bool Function(DateTime dateTime, List<int> selectedIndex)? onConfirm,
    Function(DateTime dateTime, List<int> selectedIndex)? onChange,
    Function()? onDismiss,
    Function()? onCancel,
  }) {
    return showModalKqBottomSheet(
      context: KqCoreGlobal.globalContext,
      backgroundColor: Colors.transparent,
      barrierColor: Colors.black.withOpacity(0.2),
      isScrollControlled: true,
      builder: (context) => KqDatePickerBottomSheet(
          initialDateTime: initialDateTime ?? DateTime.now(),
          pickerMode: KqDateTimePickerMode.time,
          minDateTime: minDateTime,
          maxDateTime: maxDateTime,
          leftBtnText: leftBtnText,
          rightBtnText: rightBtnText,
          pickerTitleConfig: KqPickerTitleConfig(
              titleContent: title ?? KqIntl.currentResource.pleaseChooseTime),
          dateFormat: KqIntl.currentResource.hhMMss,
          onConfirm: onConfirm,
          onCancel: onCancel,
          onChange: onChange),
    ).then((value) => {onDismiss?.call()});
  }

  /// 日期时间选择底部弹窗
  static showDateTimePicker({
    String? title,
    bool withSecond = true,
    bool withMinute = true,
    DateTime? minDateTime,
    DateTime? maxDateTime,
    DateTime? initialDateTime,
    String? leftBtnText,
    String? rightBtnText,
    bool Function(DateTime dateTime, List<int> selectedIndex)? onConfirm,
    Function(DateTime dateTime, List<int> selectedIndex)? onChange,
    Function()? onDismiss,
    Function()? onCancel,
  }) {
    showModalKqBottomSheet(
      context: KqCoreGlobal.globalContext,
      backgroundColor: Colors.transparent,
      barrierColor: Colors.black.withOpacity(0.2),
      isScrollControlled: true,
      builder: (context) => KqDatePickerBottomSheet(
          initialDateTime: initialDateTime ?? DateTime.now(),
          pickerMode: KqDateTimePickerMode.datetime,
          minDateTime: minDateTime,
          maxDateTime: maxDateTime,
          leftBtnText: leftBtnText,
          rightBtnText: rightBtnText,
          pickerTitleConfig: KqPickerTitleConfig(
              titleContent: title ?? KqIntl.currentResource.pleaseChooseTime),
          dateFormat:
              '${KqIntl.currentResource.yyyyMMdd},${KqIntl.currentResource.hh}${withMinute ? ':${KqIntl.currentResource.mm}' : ''}${withSecond ? ':${KqIntl.currentResource.ss}' : ''}',
          onConfirm: onConfirm,
          onCancel: onCancel,
          onChange: onChange),
    ).then((value) => {onDismiss?.call()});
  }

  /// 日期范围选择
  static showDateRangePicker({
    String? title,
    DateTime? minDateTime,
    DateTime? maxDateTime,
    DateTime? initialStartDateTime,
    DateTime? initialEndDateTime,
    String? hintText,
    String? leftBtnText,
    String? rightBtnText,
    double? resultFontSize,
    bool isSelectEndTime = false,
    List<Widget>? customHeaders,
    BuildContext? context,
    required bool Function(DateTime startDatetime, DateTime endDatetime)
        onConfirm,
    Function(DateTime dateTime)? onStartTimeChange,
    Function(DateTime dateTime)? onEndTimeChange,
    Function()? onDismiss,
    Function()? onCancel,
  }) {
    return showModalKqBottomSheet(
      context: context ?? KqCoreGlobal.globalContext,
      backgroundColor: Colors.transparent,
      barrierColor: Colors.black.withOpacity(0.2),
      isScrollControlled: true,
      builder: (context) => KqDateRangePickerBottomSheet(
        initialStartDateTime: initialStartDateTime ?? DateTime.now(),
        initialEndDateTime: initialEndDateTime ?? DateTime.now(),
        pickerMode: KqDateTimePickerMode.date,
        minDateTime: minDateTime,
        maxDateTime: maxDateTime,
        leftBtnText: leftBtnText,
        rightBtnText: rightBtnText,
        hintText: hintText,
        customHeaders: customHeaders,
        resultFontSize: resultFontSize,
        isSelectEndTime: isSelectEndTime,
        pickerTitleConfig: KqPickerTitleConfig(
            titleContent: title ?? KqIntl.currentResource.pleaseChooseTime),
        pickerFormat: KqIntl.currentResource.yyyyMMdd,
        dateFormat: 'yyyy-MM-dd',
        onConfirm: onConfirm,
        onCancel: onCancel,
        onStartTimeChange: onStartTimeChange,
        onEndTimeChange: onEndTimeChange,
      ),
    ).then((value) => {onDismiss?.call()});
  }

  /// 时间选择对话框
  static showTimeRangePicker({
    String? title,
    DateTime? minDateTime,
    DateTime? maxDateTime,
    DateTime? initialStartDateTime,
    DateTime? initialEndDateTime,
    String? dateFormat,
    String? hintText,
    String? leftBtnText,
    String? rightBtnText,
    double? resultFontSize,
    bool isSelectEndTime = false,
    List<Widget>? customHeaders,
    bool withSecond = true,
    required bool Function(DateTime startDatetime, DateTime endDatetime)
        onConfirm,
    Function(DateTime dateTime)? onStartTimeChange,
    Function(DateTime dateTime)? onEndTimeChange,
    Function()? onDismiss,
    Function()? onCancel,
  }) {
    return showModalKqBottomSheet(
      context: KqCoreGlobal.globalContext,
      backgroundColor: Colors.transparent,
      barrierColor: Colors.black.withOpacity(0.2),
      isScrollControlled: true,
      builder: (context) => KqDateRangePickerBottomSheet(
        initialStartDateTime: initialStartDateTime ?? DateTime.now(),
        initialEndDateTime: initialEndDateTime ?? DateTime.now(),
        pickerMode: KqDateTimePickerMode.time,
        minDateTime: minDateTime,
        maxDateTime: maxDateTime,
        leftBtnText: leftBtnText,
        rightBtnText: rightBtnText,
        resultFontSize: resultFontSize,
        hintText: hintText,
        customHeaders: customHeaders,
        isSelectEndTime: isSelectEndTime,
        pickerTitleConfig: KqPickerTitleConfig(
            titleContent: title ?? KqIntl.currentResource.pleaseChooseTime),
        pickerFormat: withSecond
            ? KqIntl.currentResource.hhMMss
            : KqIntl.currentResource.hhMM,
        dateFormat: dateFormat ?? (!withSecond ? 'HH:mm' : 'HH:mm:ss'),
        onConfirm: onConfirm,
        onCancel: onCancel,
        onStartTimeChange: onStartTimeChange,
        onEndTimeChange: onEndTimeChange,
      ),
    ).then((value) => {onDismiss?.call()});
  }

  /// 日期时间选择底部弹窗
  static showDateTimeRangePicker({
    String? title,
    bool withSecond = true,
    bool withMinute = true,
    DateTime? minDateTime,
    DateTime? maxDateTime,
    DateTime? initialStartDateTime,
    DateTime? initialEndDateTime,
    String? leftBtnText,
    String? rightBtnText,
    String? dateFormat,
    String? hintText,
    double? resultFontSize,
    bool isSelectEndTime = false,
    List<Widget>? customHeaders,
    required bool Function(DateTime startDatetime, DateTime endDatetime)
        onConfirm,
    Function(DateTime dateTime)? onStartTimeChange,
    Function(DateTime dateTime)? onEndTimeChange,
    Function()? onDismiss,
    Function()? onCancel,
  }) {
    showModalKqBottomSheet(
      context: KqCoreGlobal.globalContext,
      backgroundColor: Colors.transparent,
      barrierColor: Colors.black.withOpacity(0.2),
      isScrollControlled: true,
      builder: (context) => KqDateRangePickerBottomSheet(
        initialStartDateTime: initialStartDateTime ?? DateTime.now(),
        initialEndDateTime: initialEndDateTime ?? DateTime.now(),
        pickerMode: KqDateTimePickerMode.datetime,
        minDateTime: minDateTime,
        maxDateTime: maxDateTime,
        hintText: hintText,
        leftBtnText: leftBtnText,
        rightBtnText: rightBtnText,
        customHeaders: customHeaders,
        resultFontSize: resultFontSize,
        isSelectEndTime: isSelectEndTime,
        pickerTitleConfig: KqPickerTitleConfig(
            titleContent: title ?? KqIntl.currentResource.pleaseChooseTime),
        pickerFormat:
            '${KqIntl.currentResource.yyyyMMdd},${KqIntl.currentResource.hh}${withMinute ? ':${KqIntl.currentResource.mm}' : ''}${withSecond ? ':${KqIntl.currentResource.ss}' : ''}',
        dateFormat: dateFormat ??
            (!withMinute
                ? 'yyyy-MM-dd HH'
                : (withSecond ? 'yyyy-MM-dd HH:mm:ss' : 'yyyy-MM-dd HH:mm')),
        onConfirm: onConfirm,
        onCancel: onCancel,
        onStartTimeChange: onStartTimeChange,
        onEndTimeChange: onEndTimeChange,
      ),
    ).then((value) => {onDismiss?.call()});
  }

  /// 多层级选择
  static showLinkagePicker({
    String? title,
    String? leftBtnText,
    String? rightBtnText,
    List<Widget>? customHeaders,
    List<int>? initSelect,
    required int totalLevel,
    required String? Function(int level, dynamic item) showWhatInItem,
    required List<dynamic> Function(int fillLevel, List<dynamic>? lastLevelData,
            int? lastLevelSelectIndex, dynamic lastLevelSelectData)
        onFillData,
    required bool Function(List<int> selectIndex, List<dynamic> selectData)
        onConfirm,
    Function()? onDismiss,
    Function()? onCancel,
    bool? showBottomButton,
    bool? canPop,
  }) {
    return showModalKqBottomSheet(
        context: KqCoreGlobal.globalContext,
        backgroundColor: Colors.transparent,
        barrierColor: Colors.black.withOpacity(0.2),
        isScrollControlled: true,
        builder: (context) => KqLinkagePickerBottomSheet(
              totalLevel: totalLevel,
              initSelect: initSelect,
              onFillData: onFillData,
              showWhatInItem: showWhatInItem,
              pickerTitleConfig: KqPickerTitleConfig(
                  titleContent: title ?? KqIntl.currentResource.pleaseChoose),
              leftBtnText: leftBtnText,
              rightBtnText: rightBtnText,
              onConfirm: onConfirm,
              onCancel: onCancel,
              showBottomButton: showBottomButton ?? false,
              canPop: canPop ?? true,
            )).then((value) => {onDismiss?.call()});
  }

  /// 显示底部列表弹出菜单
  static showActionList(
    List<KqActionListData> items, {
    String? title,
    Alignment? alignment,
    bool? showCancel,
    required Function(int index, KqActionListData item)? callback,
    Function()? onDismiss,
    Function()? onCancel,
  }) {
    showModalKqBottomSheet(
      context: KqCoreGlobal.globalContext,
      backgroundColor: Colors.transparent,
      barrierColor: Colors.black.withOpacity(0.2),
      isScrollControlled: true,
      builder: (context) => KqActionListBottomSheet(
        items: items,
        title: title,
        alignment: alignment,
        showCancel: showCancel ?? false,
        callback: callback,
        onCancel: onCancel,
      ),
    ).then((value) => {onDismiss?.call()});
  }

  /// 底部列表选择
  static showListPicker<T>(List<T> items,
      {bool barrierDismissible = true,
      String? title,
      String Function(int index, T item)? nameConvert,
      Function(int index, T item)? callback,
      Function(List<T> items, bool isSelectAll)? callbackMulti,
      String? chooseIds,
      String Function(int index, T item)? idConvert,
      bool searchEnable = false,
      bool isMultiChoose = false,
      bool Function(String searchText, T item)? onSearchItem,
      Function()? onDismiss}) {
    if (items.isEmpty) {
      return;
    }
    showModalKqBottomSheet(
        context: KqCoreGlobal.globalContext,
        backgroundColor: Colors.transparent,
        barrierColor: Colors.black.withOpacity(0.2),
        isScrollControlled: true,
        builder: (context) {
          return KqListPickerBottomSheet(
              items: items,
              nameConvert: nameConvert,
              searchEnable: searchEnable,
              onSearchItem: onSearchItem,
              isMultiChoose: isMultiChoose,
              title: title,
              idConvert: idConvert,
              chooseIds: chooseIds,
              callbackMulti: (items, isSelectAll) {
                Navigator.pop(context);
                callbackMulti?.call(items, isSelectAll);
              },
              callback: (index, item) {
                Navigator.pop(context);
                if (callback != null) {
                  callback(index, item);
                }
              });
        }).then((value) => onDismiss?.call());
  }

  /// 选择组弹窗
  /// isShowBottom: 多选的时候 才展示底部
  static showOptionsPicker<T>(
      {required String title,
      required List<T> items,
      int columns = 3,
      double? childAspectRatio,
      double? crossAxisSpacing,
      double? mainAxisSpacing,
      int maxRows = 4,
      Color? bgColor,
      bool barrierDismissible = true,
      bool isShowBottom = false,
      String? chooseIds,
      String Function(int index, T item)? nameConvert,
      bool Function(int index, T item)? statusConvert,
      String Function(int index, T item)? idConvert,
      Widget Function()? customBottomBuilder,
      Function(List<T> chooses)? moreCallback,
      Function(T item)? singleCallback,
      TextStyle? titleStyle,
      Function()? onDismiss}) {
    if (items.isEmpty) {
      return;
    }
    showModalKqBottomSheet(
        context: KqCoreGlobal.globalContext,
        barrierColor: Colors.black.withOpacity(0.2),
        backgroundColor: Colors.transparent,
        isScrollControlled: true,
        builder: (context) {
          return KqOptionsBottomSheet(
            title: title,
            items: items,
            columns: columns,
            childAspectRatio: childAspectRatio,
            crossAxisSpacing: crossAxisSpacing,
            mainAxisSpacing: mainAxisSpacing,
            maxRows: maxRows,
            bgColor: bgColor,
            titleStyle: titleStyle,
            isShowBottom: isShowBottom,
            chooseIds: chooseIds,
            nameConvert: nameConvert,
            statusConvert: statusConvert,
            idConvert: idConvert,
            customBottomBuilder: customBottomBuilder,
            moreCallback: (chooses) {
              Navigator.pop(context);
              if (moreCallback != null) {
                moreCallback(chooses);
              }
            },
            singleCallback: (item) {
              Navigator.pop(context);
              if (singleCallback != null) {
                singleCallback(item);
              }
            },
          );
        }).then((value) => onDismiss?.call());
  }
}

class KqPickerTitleConfig {
  /// DateTimePicker theme.
  ///
  /// [cancel] Custom cancel widget.
  /// [confirm] Custom confirm widget.
  /// [title] Custom title widget. If specify a title widget, the cancel and confirm widgets will not display. Must set [titleHeight] value for custom title widget.
  /// [showTitle] Whether display title widget or not. If set false, the default cancel and confirm widgets will not display, but the custom title widget will display if had specified one custom title widget.
  /// [titleContent] Title content
  const KqPickerTitleConfig({
    this.cancel,
    this.confirm,
    this.title,
    this.showTitle = true,
    this.titleContent,
  });

  static const KqPickerTitleConfig Default = const KqPickerTitleConfig();

  /// Custom cancel [Widget].
  final Widget? cancel;

  /// Custom confirm [Widget].
  final Widget? confirm;

  /// Custom title [Widget]. If specify a title widget, the cancel and confirm widgets will not display.
  final Widget? title;

  /// Whether display title widget or not. If set false, the default cancel and confirm widgets will not display, but the custom title widget will display if had specified one custom title widget.
  final bool showTitle;

  final String? titleContent;

  KqPickerTitleConfig copyWith({
    Widget? cancel,
    Widget? confirm,
    Widget? title,
    bool? showTitle,
    String? titleContent,
  }) {
    return KqPickerTitleConfig(
      cancel: cancel ?? this.cancel,
      confirm: confirm ?? this.confirm,
      title: title ?? this.title,
      showTitle: showTitle ?? this.showTitle,
      titleContent: titleContent ?? this.titleContent,
    );
  }
}
